import config from '../config'

function formatNumber(n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const t1 = [year, month, day].map(formatNumber).join('-')

  return `${t1}`
}

export function request(url, method, data, needLoading = 'defaultLoading', header) {
  return new Promise((resolve, reject) => {
    if (needLoading === 'showLoading' || needLoading === 'defaultLoading') {
      wx.showToast({
        icon: 'loading',
        title: '正在加载'
      })
    }
    const TOKEN = wx.getStorageSync('token')
    if (TOKEN) {
      header = { Authorization: 'Bearer ' + TOKEN }
    }
    wx.request({
      data,
      method,
      url: config.host + url,
      header: header,
      success(res) {
        if (res.statusCode === 200) {
          resolve(res)
        } else {
          wx.showToast({
            title: '数据请求失败,请重新授权',
            icon: 'none',
            duration: 1500
          })
          try {
            wx.removeStorageSync("token");
          } catch (err) { }
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/buffer/main'
            })
          }, 1500);
        }
      },
      fail() { },
      complete() {
        if (needLoading === 'hideLoadinig' || needLoading === 'defaultLoading') {
          wx.hideToast()
        }
      }
    })
  })
}

export function wxLogin() {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        if (res.code) {
          resolve(res.code)
        } else {
          reject(res)
        }
      }
    })
  })
}

export function judgeUser() {
  return new Promise((resolve, reject) => {
    request('/v1/personal-center/is-user-login', 'get', {}, null).then(res => {
      if (res.statusCode === 200) {
        resolve(res)
      }
    })
  })
}

export default {
  formatNumber,
  formatTime
}
